package moni.anyou.com.view.view;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.Gson;
import com.scu.miomin.shswiperefresh.core.SHSwipeRefreshLayout;

import org.json.JSONObject;
import org.kymjs.aframe.http.KJHttp;
import org.kymjs.aframe.http.KJStringParams;
import org.kymjs.aframe.http.StringCallBack;

import java.util.ArrayList;
import java.util.List;

import moni.anyou.com.view.R;
import moni.anyou.com.view.base.BaseActivity;
import moni.anyou.com.view.base.BaseInfo;
import moni.anyou.com.view.bean.DynamicsTempItems;
import moni.anyou.com.view.bean.request.ReqDynamicsCommentBean;
import moni.anyou.com.view.bean.request.ReqSentDynamicsBean;
import moni.anyou.com.view.bean.request.ReqsLikeTeacherBean;
import moni.anyou.com.view.bean.response.ResDynamicsBean;
import moni.anyou.com.view.config.SysConfig;
import moni.anyou.com.view.tool.AppTools;
import moni.anyou.com.view.tool.KeyBoardTools;
import moni.anyou.com.view.tool.ToastTools;
import moni.anyou.com.view.view.dynamics.adapter.SearchItemsAdapter;
import moni.anyou.com.view.widget.NetProgressWindowDialog;
import moni.anyou.com.view.widget.dialog.PopCommentSent;
import moni.anyou.com.view.widget.recycleview.MyRecycleView;
import moni.anyou.com.view.widget.utils.view.ViewUtil;

public class SearchActivity extends BaseActivity  implements View.OnClickListener{
    private NetProgressWindowDialog window;
    private TextView tvLeft;
    private TextView tvTitle;
    private MyRecycleView lvDynamics;
    private SHSwipeRefreshLayout swipeRefreshLayout;
    private SearchItemsAdapter searchItemAdapter;
    private PopCommentSent mPopCommentSent;
    private List<DynamicsTempItems> mItems;
    private int pageSize = 5;
    private int pageNo = 1;
    private int typeid = 1;
    int totalCount = 0;
    private EditText editText;
    BaseInfo mBaseInfo;
    private String keyword = "";
    private Handler taskHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            keyword =  editText.getText().toString();
            getData();
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search2);
        initView();


    }
    @Override
    public void initView() {
        super.initView();
        mContext = this;
        mViewUtil = new ViewUtil(this);
        initSwipeRefreshLayout();
        mPopCommentSent = new PopCommentSent(this, this);
        window = new NetProgressWindowDialog(this);
        tvLeft = (TextView)findViewById(R.id.iv_left);
        tvTitle = (TextView) findViewById(R.id.page_title);
        tvTitle.setText("搜索");
        lvDynamics = (MyRecycleView) findViewById(R.id.lv_dynamics);
        editText = (EditText) findViewById(R.id.editText);
        mItems = new ArrayList<>();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        lvDynamics.setLayoutManager(linearLayoutManager);
        searchItemAdapter = new SearchItemsAdapter(this);
        lvDynamics.setAdapter(searchItemAdapter);

        tvLeft.setOnClickListener(this);
        searchItemAdapter.setComentClickListener(new SearchItemsAdapter.ComentClickListener() {
            @Override
            public void onItemClick(int position, ResDynamicsBean.ListBean data) {
                // ToastTools.showShort(mContext, "" + position);
                mPopCommentSent.showAtLocation(findViewById(R.id.pop_need), Gravity.CENTER, 0, 0);
                mPopCommentSent.position = position;
                mPopCommentSent.data = data;
                mPopCommentSent.isShowing();
                KeyBoardTools.openKeybord(mPopCommentSent.etComments, mContext);

            }
        });
        searchItemAdapter.setOnDeleteClickListener(new SearchItemsAdapter.OnDeleteClickListener() {
            @Override
            public void onItemClick(int position, ResDynamicsBean.ListBean data) {
                postDeleteDynamics(data, position);
            }
        });
        searchItemAdapter.setIPraiseClickListener(new SearchItemsAdapter.IPraiseClickListener() {
            @Override
            public void onItemClick(int position, ResDynamicsBean.ListBean data) {
                postLikeArticle(position, data);
            }
        });
        searchItemAdapter.setDownloadClickListener(new SearchItemsAdapter.DownloadClickListener() {
            @Override
            public void onItemClick(int position, ResDynamicsBean.ListBean data) {

            }
        });

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //每次内容改变时，先移除前面的消息，避免太过频繁的搜索
                taskHandler.removeMessages(1);
                if (s.length() <= 0){
                    return;
                }
                //间隔500后发送消息
                taskHandler.sendEmptyMessageDelayed(1, 500);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }
    @Override
    public void setAction() {

    }


    //@Override
    //public void onResume() {
   //     super.onResume();
   //     getData();
    //}
    public void getData() {
        KJHttp kjh = new KJHttp();
        KJStringParams params = new KJStringParams();
        //String cmdPara = new ReqPageBean("17", SysConfig.uid, SysConfig.token, "" + pageNo, "" + pageSize).ToJsonString();
        String cmdPara = "{\"cmd\":\"17\",\"uid\":\"" + SysConfig.uid + "\",\"token\":\"" + SysConfig.token +"\",\"pageNo\":\"" + pageNo + "\",\"pageSize\":\"" + pageSize  +"\",\"typeid\":\"0\",\"keyword\":\"" + keyword + "\",\"cid\":\"" + SysConfig.cid + "\"}";
        params.put("sendMsg", cmdPara);

        kjh.urlGet(SysConfig.ServerUrl, params, new StringCallBack() {
            @Override
            public void onSuccess(String t) {
                try {
                    JSONObject jsonObject = new JSONObject(t);
                    int result = Integer.parseInt(jsonObject.getString("result"));
                    totalCount = jsonObject.getInt("totalCount");
                    if (result >= 1) {
                        ResDynamicsBean temp = new Gson().fromJson(t, ResDynamicsBean.class);
                        //if (pageNo > 1) {
                            searchItemAdapter.AddDatas(AppTools.getDynamicsItemBean(temp));
                            swipeRefreshLayout.finishLoadmore();
                       // } else {
                        //    swipeRefreshLayout.finishRefresh();
                       //     List<ResDynamicsBean.ListBean> bean = new ArrayList<ResDynamicsBean.ListBean>();
                       //     bean.add(new ResDynamicsBean.ListBean());

                      //      bean.addAll(AppTools.getDynamicsItemBean(temp));
                        //    searchItemAdapter.setDatas(bean);
                       // }


                    } else {
                        if (result == -2) {
                            AppTools.jumptoLogin(mBaseActivity, result);
                        }
                        Toast.makeText(mContext, jsonObject.get("retmsg").toString(), Toast.LENGTH_LONG).show();
                    }
                } catch (Exception ex) {
                    Toast.makeText(mContext, "数据请求失败", Toast.LENGTH_LONG).show();
                }

            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Toast.makeText(mContext, "网络异常，请稍后再试", Toast.LENGTH_LONG).show();

            }
        });


    }

    private void initSwipeRefreshLayout() {
        swipeRefreshLayout = (SHSwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);

        LayoutInflater inflater = LayoutInflater.from(this);
        final View view = inflater.inflate(R.layout.refresh_view, null);
        final TextView textView = (TextView) view.findViewById(R.id.title);
        swipeRefreshLayout.setFooterView(view);
        swipeRefreshLayout.setOnRefreshListener(new SHSwipeRefreshLayout.SHSOnRefreshListener() {
            @Override
            public void onRefresh() {
                pageNo = 1;
                getData();
            }

            @Override
            public void onLoading() {

                if (pageNo * pageSize < totalCount) {
                    pageNo++;
                    getData();
                } else {
                    swipeRefreshLayout.finishLoadmore();
                    ToastTools.showShort(mContext, "没有更多了");
                }
            }

            /**
             * 监听下拉刷新过程中的状态改变
             * @param percent 当前下拉距离的百分比（0-1）
             * @param state 分三种状态{NOT_OVER_TRIGGER_POINT：还未到触发下拉刷新的距离；OVER_TRIGGER_POINT：已经到触发下拉刷新的距离；START：正在下拉刷新}
             */
            @Override
            public void onRefreshPulStateChange(float percent, int state) {
                switch (state) {
                    case SHSwipeRefreshLayout.NOT_OVER_TRIGGER_POINT:
                        swipeRefreshLayout.setLoaderViewText("");
                        break;
                    case SHSwipeRefreshLayout.OVER_TRIGGER_POINT:
                        swipeRefreshLayout.setLoaderViewText("");
                        break;
                    case SHSwipeRefreshLayout.START:
                        swipeRefreshLayout.setLoaderViewText("");
                        break;
                }
            }

            @Override
            public void onLoadmorePullStateChange(float percent, int state) {
                switch (state) {
                    case SHSwipeRefreshLayout.NOT_OVER_TRIGGER_POINT:
                        textView.setText("上拉加载");
                        break;
                    case SHSwipeRefreshLayout.OVER_TRIGGER_POINT:
                        textView.setText("松开加载");
                        break;
                    case SHSwipeRefreshLayout.START:
                        textView.setText("正在加载...");
                        break;
                }
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_left:
                this.finish();
                break;
            case R.id.btn_pop_sent:
                postAddCommentDynamics(mPopCommentSent.data, mPopCommentSent.position);
                KeyBoardTools.closeKeybord(mPopCommentSent.etComments, mContext);
                mPopCommentSent.backgroundAlpha(1f);
                mPopCommentSent.dismiss();
                break;
            default:
                break;
        }
    }

    public void postDeleteDynamics(ResDynamicsBean.ListBean bean, final int position) {
        KJHttp kjh = new KJHttp();
        KJStringParams params = new KJStringParams();
        String cmdPara = new ReqSentDynamicsBean("18", SysConfig.uid, SysConfig.token, ReqSentDynamicsBean.TYPEID_DELETE, bean.articleid, "", "","","","","0").ToJsonString();
        params.put("sendMsg", cmdPara);
        window.ShowWindow();
        kjh.urlGet(SysConfig.ServerUrl, params, new StringCallBack() {
            @Override
            public void onSuccess(String t) {
                Log.d(TAG, "onSuccess: " + t);
                try {
                    JSONObject jsonObject = new JSONObject(t);
                    //Toast.makeText(mContext, t, Toast.LENGTH_LONG).show();
                    int result = Integer.parseInt(jsonObject.getString("result"));
                    if (result >= 1) {
                        searchItemAdapter.removeDynamics(position);
                        Toast.makeText(mContext, "删除成功", Toast.LENGTH_LONG).show();
                    } else {
                        if (result == -2) {
                            AppTools.jumptoLogin(mBaseActivity, result);
                        }
                        else {
                            Toast.makeText(mContext, jsonObject.get("retmsg").toString(), Toast.LENGTH_LONG).show();
                        }
                    }
                } catch (Exception ex) {
                    Toast.makeText(mContext, "数据请求失败", Toast.LENGTH_LONG).show();

                }
                window.closeWindow();
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Toast.makeText(mContext, "网络异常，请稍后再试", Toast.LENGTH_LONG).show();
                window.closeWindow();
            }
        });


    }


    //添加评论
    public void postAddCommentDynamics(final ResDynamicsBean.ListBean bean, final int position) {


        if (TextUtils.isEmpty(mPopCommentSent.etComments.getText())) {
            ToastTools.showShort(mContext, "评论内容不能为空");
        } else {


            KJHttp kjh = new KJHttp();
            KJStringParams params = new KJStringParams();
            String cmdPara = new ReqDynamicsCommentBean("25", SysConfig.uid, SysConfig.token, bean.articleid, mPopCommentSent.etComments.getText().toString()).ToJsonString();
            params.put("sendMsg", cmdPara);
            window.ShowWindow();
            kjh.urlGet(SysConfig.ServerUrl, params, new StringCallBack() {
                @Override
                public void onSuccess(String t) {
                    Log.d(TAG, "onSuccess: " + t);
                    try {
                        JSONObject jsonObject = new JSONObject(t);
                        //Toast.makeText(mContext, t, Toast.LENGTH_LONG).show();
                        int result = Integer.parseInt(jsonObject.getString("result"));
                        if (result >= 1) {
                            String tempstr = mPopCommentSent.etComments.getText().toString();
                            bean.commentList.add(new ResDynamicsBean.CommentListBean(tempstr, mBaseInfo.nick));
                            mPopCommentSent.etComments.setText("");
                            searchItemAdapter.notifyItemChanged(position, bean);
                        } else {
                            if (result == -2) {
                                AppTools.jumptoLogin(mBaseActivity, result);
                            }
                            else {
                                Toast.makeText(mContext, jsonObject.get("retmsg").toString(), Toast.LENGTH_LONG).show();
                            }
                        }
                    } catch (Exception ex) {
                        Toast.makeText(mContext, "数据请求失败", Toast.LENGTH_LONG).show();

                    }
                    window.closeWindow();
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    Toast.makeText(mContext, "网络异常，请稍后再试", Toast.LENGTH_LONG).show();
                    window.closeWindow();
                }
            });

        }
    }

    public void postLikeArticle(final int position, final ResDynamicsBean.ListBean bean) {
        KJHttp kjh = new KJHttp();
        KJStringParams params = new KJStringParams();
        String cmdPara = new ReqsLikeTeacherBean("15", SysConfig.uid, SysConfig.token, bean.articleid, "article").ToJsonString();
        params.put("sendMsg", cmdPara);
        window.ShowWindow();
        kjh.urlGet(SysConfig.ServerUrl, params, new StringCallBack() {
            @Override
            public void onSuccess(String t) {
                Log.d(TAG, "onSuccess: " + t);
                try {
                    JSONObject jsonObject = new JSONObject(t);
                    int result = Integer.parseInt(jsonObject.getString("result"));
                    if (result >= 1) {
                        bean.likeuser = AppTools.likeUsers(bean);
                        searchItemAdapter.notifyItemChanged(position, bean);
                    } else {
                        if (result == -2) {
                            AppTools.jumptoLogin(SearchActivity.this, result);
                        }
                        else {
                            Toast.makeText(SearchActivity.this, jsonObject.get("retmsg").toString(), Toast.LENGTH_LONG).show();
                        }
                    }
                } catch (Exception ex) {
                    Toast.makeText(SearchActivity.this, "数据请求失败", Toast.LENGTH_LONG).show();

                }
                window.closeWindow();
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Toast.makeText(SearchActivity.this, "网络异常，请稍后再试", Toast.LENGTH_LONG).show();

                window.closeWindow();
            }
        });
    }
}
